package com.jm.product.utils;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class UploadFileUtils {
	
	private static final Logger log = LoggerFactory.getLogger(UploadFileUtils.class) ;
	
	/**
	 * 文件上传，可改为云存储
	 * @param file
	 * @param uploadRootPath
	 * @param uploadFolder
	 * @return
	 * @throws Exception
	 */
	public static String upload(MultipartFile file, String uploadRootPath, String uploadFolder) throws Exception {
		if ((file == null) || (uploadRootPath == null)) {
	      throw new IllegalArgumentException("file or filePath object is null");
	    }
	    if (uploadFolder == null) {
	      throw new IllegalArgumentException("uploadFolder is null");
	    }
	    String fileName = file.getOriginalFilename();
	    if (!UploadFileUtils.isAllowUp(fileName)) {
	      throw new IllegalArgumentException("不被允许的上传文件类型");
	    }
	    
	    String ext = UploadFileUtils.getFileExt(fileName);
	    DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	    String newFileName = format.format(new java.util.Date()) + UploadFileUtils.getRandStr(4) + "." + ext;
	    
	    String filePath = uploadRootPath + "/" + uploadFolder ;
	    UploadFileUtils.createFolder(filePath);
	    File storePath = new File(filePath + "/" + newFileName);
	    file.transferTo(storePath);
	    
	    String path = uploadFolder + "/" + newFileName ;
	    return path;
	}

	/**
	 * 是否是允许上传类型
	 * @param logoFileName
	 * @return
	 */
	public static boolean isAllowUp(String logoFileName) {
	    logoFileName = logoFileName.toLowerCase();
	    String allowTYpe = "gif,jpg,bmp,swf,png,rar,doc,docx,xls,xlsx,pdf,zip,ico,txt";
	    if ((!logoFileName.trim().equals("")) && (logoFileName.length() > 0)) {
	      String ex = logoFileName.substring(logoFileName.lastIndexOf(".") + 1, logoFileName.length());
	      
	      return allowTYpe.toUpperCase().indexOf(ex.toUpperCase()) >= 0;
	    }
	    return false;
	}
	
	/**
	 * 创建目录
	 * @param filePath
	 */
	public static void createFolder(String filePath) {
	    try {
	      File file = new File(filePath);
	      if (!file.exists()) {
	        file.mkdirs();
	      }
	    } catch (Exception ex) {
	      System.err.println("Make Folder Error:" + ex.getMessage());
	    }
	}
	
	/**
	 * 删除文件
	 * @param filePath
	 */
	public static void delete(String filePath) {
	    try {
	      File file = new File(filePath);
	      if (file.exists()) {
	        if (file.isDirectory()) {
	          FileUtils.deleteDirectory(file);
	        } else {
	          file.delete();
	        }
	        log.info("删除文件：" + file.getAbsolutePath());
	      }
	    } catch (Exception ex) {
	      ex.printStackTrace();
	    }
	}
	
	/**
	 * 得到文件后缀
	 * @param fileName
	 * @return
	 */
	public static String getFileExt(String fileName) {
		if(StringUtils.isBlank(fileName)) return "";
	    int potPos = fileName.lastIndexOf('.') + 1;
	    String type = fileName.substring(potPos, fileName.length());
	    return type;
	}
	
	/**
	 * 返回n位随机数
	 * @param n
	 * @return
	 */
	public static String getRandStr(int n) {
	    Random random = new Random();
	    String sRand = "";
	    if(n < 1) n = 1 ;
	    for (int i = 0; i < n; i++) {
	      String rand = String.valueOf(random.nextInt(10));
	      sRand = sRand + rand;
	    }
	    return sRand;
	}
}
